import { setStorage } from '../utils/utils'
import { encode } from 'js-base64'
window.electron?.ipcRenderer.on('respWMIC', function (event, arg) {
  let _cmd = ''
  if (arg) {
    arg.forEach((v) => {
      _cmd += String.fromCharCode(v)
    })
    const _wmArr = _cmd.split('" "')
    const token = _wmArr.find((_v) => _v.includes('--remoting-auth-token='))?.split('=')[1] || ''
    const port = _wmArr.find((_v) => _v.includes('--app-port='))?.split('=')[1] || ''
    if (port) {
      setStorage({
        token: `Basic ${encode(`riot:${token}`)}`,
        port
      })
    } else {
      localStorage.clear()
    }
  }
})

export const sendWMIC = () => {
  window.electron.ipcRenderer.invoke('sendWMIC')
}
